const textSelection = window.getSelection();
let currentCallback = null;
let positionMap = {
  downX: 0,
  downY: 0,
};
let currentTargetDom = null;
let isMove = true;
// const handleMouseMove = (e) => {
//   isMove = true;
//   console.log(e);
// };
const handleMouseUp = (e) => {
  const { anchorOffset, extentOffset, focusNode } = textSelection;
  // 如果开始和结束一样说明只是普通点击
  if (e.clientX === positionMap.downX && e.clientY === positionMap.downY) {
    // textSelection.removeAllRanges();
    positionMap = {
      downX: 0,
      downY: 0,
    };
    return;
  }
  if (extentOffset === anchorOffset) {
    textSelection.removeAllRanges();
    return;
  }
  // 如果选中的节点存在 并且开始和结束指针其中一个有值
  if (focusNode && (extentOffset || anchorOffset)) {
    currentCallback();
  }
  // 移出鼠标点击之后的事件
  currentTargetDom.removeEventListener("mouseup", handleMouseUp);
};
// 鼠标点击之后触发
const handleMouseDown = (e) => {
  if (e.buttons === 1) {
    positionMap.downX = e.clientX;
    positionMap.downY = e.clientY;
    currentTargetDom.addEventListener("mouseup", handleMouseUp);
  }
};
// 初始化
export function listenTextSelectInit(callback, targetDom) {
  currentCallback = callback;
  currentTargetDom = targetDom;
  // 监听
  currentTargetDom.addEventListener("mousedown", handleMouseDown);
}
// 销毁监听
export function listenTextSelectDestory() {
  currentCallback = null;
  // currentTargetDom.removeEventListener("mousedown");
  currentTargetDom = null;
}
